<template>
  <div style="width: 100%;">
    <el-upload
      v-if="!value"
      ref="upload"
      v-bind="$attrs"
      :disabled="!mixEditable"
      :headers="headers"
      listType="button"
      :http-request="uploadFile"
      :on-success="success"
      :on-error="error"
      v-on="$listeners"
      :show-file-list="false"
    >
      <el-button type="primary">上传文件</el-button>
    </el-upload>
    <div v-else>
      <div v-for="item in valueArray" :key="item.id" class="word_container">
        <div class="left">{{ item.name }}</div>
        <el-button @click="handlerProcessingForm(item)" type="primary">生成word文档</el-button>
      </div>
    </div>
    <el-dialog
      title="生成word文档"
      :visible.sync="dialogVisiable"
      width="700"
      :close-on-click-modal="false"
      :showFullScreenButton="true"
      append-to-body
      :showFooter="false"
      :before-close="handleClose"
    >
      <div style="text-align: center;padding-top: 10px;">
        <el-button type="primary" @click="previewWord">预览</el-button>
        <el-button type="primary">
          <a :href="downloadUrl" @click="downloadThen">下载</a>
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import routerContextPath from '../../mixins/router-context-path.js'
export default {
  name: 'customWord',
  components: {},
  mixins: [routerContextPath],
  props: {
    value: null,
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    headers: {
      default: () => {},
    },
    sampleList: {
      type: Array,
      default: () => []
    },
    fileName: {
      type: String,
      default: ''
    }
  },
  computed: {
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    valueArray() {
      const arr = this.value && this.value.split(',').map(i => {
        const obj = i.split('/')
        return {
          id: obj[0],
          name: obj[1],
          type: obj[2]
        }
      }) || []
      console.log(arr,'==arr')
      return arr
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
  },
  data() {
    return {
      dialogVisiable: false,
      downloadUrl: '',
      wordId: ''
    }
  },
  created(){
  },
  watch: {
  },
  methods: {
    async handlerProcessingForm(item) {
      // const prefix = 'http://121.36.242.165:28084'
      const prefix = window.location.origin
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.wrapHeader, [{
        taskId: String(Math.random()*100000000).slice(0,6),
        templateFilename: item.name,
        sampleList: this.sampleList,
        // sampleList: [{bookmark: "AffixName",type: "TEXT",text: "电影"},{bookmark: "AffixNames",type: "TEXT",text: "文艺片"}],
        templateUrl: prefix + `/XFfileServer/fileDownload?id=${item.id}`,
        // http://121.36.242.165:28084/XFfileServer/fileDownload?id=517
      }])
      const { msg, data, code } = resp.data
      if (code === 200) {
        await this.downloadFormat(data, item)
      } else {
        this.$message.error(msg)
      }
    },
    async downloadFormat(info, item) {
      const target = item.name.slice(item.name.lastIndexOf('.') + 1)
      const { downloadId, routerKey } = info
      const user = localStorage.getItem('user')
      const data = {
        downloadId,
        routeKey: routerKey,
        userName: JSON.parse(user).userName,
        target,
        fileName: this.fileName || item.name
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.operateDocumentResultDownload, data)
      if (!resp.error) {
        this.downloadUrl = resp.data.downloadUrl
        this.wordId = resp.data.fileId
        this.openAction()
      }
    },
    openAction() {
      this.dialogVisiable = true
    },
    previewWord() {
      this.previewApp({
        id: this.wordId,
        type: this.fileType
      })
    },
    handleClose() {
      this.dialogVisiable = false
    },
    async previewApp(item) {
      const user = localStorage.getItem('user')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkView, {
        fileId: item.id,
        type: item.type || 'w',
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        // this.setToken(data.link)
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=preview`)
        // window.open(data.link)
      } else {
        this.$message.error(msg)
      }
    },
    async uploadFile(file){
      let params= new FormData()
      const user = localStorage.getItem('user')
      params.append('attachments',file.file)
      params.append('userName', JSON.parse(user).userName)
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.XFFileController.fileUpload, params)
      if (!resp.error && resp.data) {
        const { id, name } = resp.data[0]
        const val = id + '/' + name + '/w'
        this.$emit('input', val)
        this.fileList = []
        this.$message({
            type: 'success',
            message: '上传成功!'
        })
      }
    },
    error(err, file, fileList) {
      this.$emit('uploadError',{err, file, fileList})
    },
    success(response, file, fileList) {

    },
    // 场景：下载之后还可能下载随带文件，抛出事件
    downloadThen() {
      this.$emit('downloadSuccess')
    }
  }
}
</script>

<style lang="scss" scoped>
.word_container {
  display: flex;
  .left {
    flex: 1;
  }
  .el-button {
    margin-left: 5px;
  }
}
a {
  text-decoration: none;
  color: #fff;
}
a:hover,a:link {
  color: #fff;
}
.el-button.el-button--primary:hover {
  a {
    text-decoration: none;
    color: #fff;
  }
}
</style>
